<?php
App::import('Controller','Assets.CmsAssets');
class EventAssetsController extends CmsAssetsController
{
	var $name = 'EventAssets';
	var $components =array('Auth','Session','RequestHandler');
	function beforeFilter()
	{
		parent::beforeFilter();
		$this->Auth->allow('index','add','all');
		$this->indexMethods = cr('indexMethods.EventAsset');
	}

	function delete($id)
	{
		$eventId = $this->EventAsset->field('event_id',array("id"=>$id));
		$this->EventAsset->delete($id);
		$this->EventAsset->Event->clearRecordCache($eventId,true);
		if(!$this->RequestHandler->isAjax())
		{
			$this->successMsg(__("Image has been deleted"));
			$url = $this->referer(array("action"=>"index","my"));
			$this->redirect($url);
		}else
		{
			$this->_stop();
		}
		$this->redirect("/");
	}
	function admin_delete($id = null)
	{
		$eventId = $this->EventAsset->field('event_id',array('EventAsset.id'=>$id));
		$this->EventAsset->Event->clearRecordCache($eventId,true);

		$this->EventAsset->id = $id;
		if($this->EventAsset->del($id))
		{
			$this->successMsg(__('Image has been deleted'));
		}else
		{
			$this->errorMsg(__('Sorry, image could not be deleted'));
		}
		$this->redirect($this->referer());
	}
	function add($id = null)
	{
		$event = $this->EventAsset->Event->find('first',array('conditions'=>array('Event.id'=>$id),'recursive'=>-1));
		if(!$event)
		{
			$this->redirect('/');
		}

		$this->set('event',$event);
		
		if($this->data && $this->data['EventAsset']['name']['name'] == '')
		{
			$this->__afterAssetFail($this->data,null);
			$this->redirect($this->referer());
		}else
		{
			$item = $this->EventAsset->Event->getItem('Event',$id);
			if(empty($item))
			{
				$this->errorMsg(__('Invalid URL'));
				$this->redirect($this->referer());
			}
			//$cnt=$this->EventAsset->query('select count(*) cnt from event_assets where event_id = '.$id);
			$cnt=$this->EventAsset->find('count',array("conditions"=>array("EventAsset.event_id"=>$id)));
			if (!empty($this->data))
			{
				$this->EventAsset->create();
				if($this->EventAsset->save($this->data,array('validate'=>'first')))
				{
					$this->__afterAssetAdd($this->data,$item);
				}
				else
				{
					$this->__afterAssetFail($this->data,$item);
				}

			}
			elseif (empty($this->data))
			{
				$redirectUrl = '/';
				$this->Session->write('redirectTo',$redirectUrl);
			}
			$this->pageTitle = sprintf(__('Upload an image  for %s %s'),'Event',$item['Event'][$this->EventAsset->Event->displayField]);
			$this->set('type','Event');
			$this->set('item_id',$id);
			$this->set('modelName','Event');
			$this->set('pageHeading',sprintf(__('Upload an image  for %s %s'),'Event',$item['Event'][$this->EventAsset->Event->displayField]));
		}
	}


	function admin_add($id = null)
	{
		$event = $this->EventAsset->Event->find('first',array('conditions'=>array('Event.id'=>$id),'recursive'=>-1));
		if(!$event)
		{
			$this->redirect('/');
		}

		$this->set('event',$event);
		if($this->data && $this->data['EventAsset']['name']['name'] == '')
		{
			$this->__afterAssetFail($this->data,null);
			$this->redirect($this->referer());
		}else
		{
			$item = $this->EventAsset->Event->getItem('Event',$id);
			if(empty($item))
			{
				$this->errorMsg(__('Invalid URL'));
				$this->redirect($this->referer());
			}
			//$cnt=$this->EventAsset->query('select count(*) cnt from event_assets where event_id = '.$id);
			$cnt=$this->EventAsset->find('count',array("conditions"=>array("EventAsset.event_id"=>$id)));
			if (!empty($this->data))
			{
				$this->EventAsset->create();
				if($this->EventAsset->save($this->data,array('validate'=>'first')))
				{
					$this->__afterAssetAdd($this->data,$item);
				}
				else
				{
					$this->__afterAssetFail($this->data,$item);
				}

			}
			elseif (empty($this->data))
			{
				$redirectUrl = '/';
				$this->Session->write('redirectTo',$redirectUrl);
			}
			$this->pageTitle = sprintf(__('Upload an image  for %s %s'),'Event',$item['Event'][$this->EventAsset->Event->displayField]);
			$this->set('type','Event');
			$this->set('item_id',$id);
			$this->set('modelName','Event');
			$this->set('pageHeading',sprintf(__('Upload an image  for %s %s'),'Event',$item['Event'][$this->EventAsset->Event->displayField]));
		}
	}

	
	
	function __afterAssetAdd($uploadedData,$itemInfo)
	{
		//$this->EventAsset->Event->clearRecordCache($itemInfo['Event']['id'],true);
		$this->successMsg(__('The image has been uploaded successfully', true));
		$this->redirect($itemInfo['Event']['viewUrl']);
	}

	function __afterAssetFail($uploadedData,$itemInfo)
	{
		$this->errorMsg(__('The image could not be saved. Please, try again.', true));
	}

	function view($id = null)
	{
		$isAdmin = false;
		if(isset($this->params['admin']))
		{
			$isAdmin = true;
		}
		$this->EventAsset->recursive = 0;
		if($isAdmin)
		{
			$assetData = $this->EventAsset->findById($id);
			$neighborCondition = array('EventAsset.event_id'=>$assetData['EventAsset']['event_id']);
		}else
		{
			$assetData = $this->EventAsset->findByIdAndStatus($id,EventAsset::PUBLISHED);
			$neighborCondition = array('EventAsset.event_id'=>$assetData['EventAsset']['event_id'],'status'=>EventAsset::PUBLISHED);
		}
		if(empty($assetData))
		{
			$this->errorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}

		$neighbors = $this->EventAsset->find('neighbors',array('conditions'=>$neighborCondition,'recursive'=>-1,'fields'=>array('id'),'callbacks'=>false));
		$event = $this->EventAsset->Event->find('first',array('conditions'=>array('Event.id'=>$assetData['EventAsset']['event_id']),'recursive'=>-1));
		
		$this->set(compact('assetData','neighbors'));
		$this->set('event',array('Event'=>$assetData['Event']));
		$this->pageTitle = sprintf(__('%s\'s Gallery'),$assetData['Event']['title']);

	}

	function admin_view($eventId = null)
	{
		$this->view($eventId);
		$this->render("view");
	}

	function admin_setAsDefault($id = null)
	{
		$this->EventAsset->recursive = -1;
		$eventAsset = $this->EventAsset->findByid($id);
		if(empty($eventAsset))
		{
			$this->errrorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}
		$this->EventAsset->id = $id;
		if($eventAsset["EventAsset"]["status"] == EventAsset::UNPUBLISHED)
		{
			$this->EventAsset->saveField('status',EventAsset::PUBLISHED);
		}
		$this->EventAsset->updateAll(array('is_default'=>0),array('EventAsset.event_id'=>$eventAsset["EventAsset"]["event_id"]));
		$setAsDefaultResponse = $this->EventAsset->saveField('is_default',1);
		if($setAsDefaultResponse)
		{
			$this->successMsg(__("Default image has been changed."));
		}else
		{
			$this->errorMsg(__("Default image could not be changed. Please try again."));
		}
		$this->EventAsset->Event->clearRecordCache($eventAsset['EventAsset']['event_id'],true);
		$this->redirect($this->referer());
	}

	function admin_changeStatus($id = null)
	{
		$this->EventAsset->recursive = -1;
		$eventAsset = $this->EventAsset->findByid($id);
		if(empty($eventAsset))
		{
			$this->errrorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}
		$this->EventAsset->id = $id;
		if($eventAsset["EventAsset"]["status"] == EventAsset::UNPUBLISHED)
		{
			$statusToSave = EventAsset::PUBLISHED;
			$successMsg = __('Image has been published.');
			$errorMsg = __('Sorry,image could not be published.');
		}else
		{
			$statusToSave = EventAsset::UNPUBLISHED;
			$successMsg = __('Image has been unpublished.');
			$errorMsg = __('Sorry,image could not be unpublished.');
		}
		if($this->EventAsset->saveField('status',$statusToSave))
		{
			$this->successMsg($successMsg);
			$this->EventAsset->Event->clearRecordCache($eventAsset['EventAsset']['event_id'],true);
		}else
		{
			$this->errorMsg($errorMsg);
		}
		$this->redirect($this->referer());
	}



	function index($type = false)
	{
		$this->paginate['order'] = array('EventAsset.created DESC');
		$this->paginate['recursive'] = 0;
		if(isset($this->params['named']['limit']))
		{
			unset($this->params['named']['limit']);
			unset($this->passedArgs['limit']);
		}
		$this->paginate['limit'] = 150;
		$this->paginate['contain'] = array("Event");
		$this->paginate['conditions']['EventAsset.status'] = EventAsset::PUBLISHED;
		$assetToShow = null;
		if(isset($this->params['named']['show']))
		{
			$assetToShow = $this->params['named']['show'];
			unset($this->params['named']['show']);
			unset($this->passedArgs['show']);
		}
		$this->set("assetToShow",$assetToShow);
		if($type)
		{
			if(in_array($type, array_keys($this->indexMethods)))
			{
				$subMethodName = $this->indexMethods[$type]['method'];
				if(isset($this->indexMethods[$type]['title']))
				{
					$this->pageTitle = __($this->indexMethods[$type]['title']);
				}
				$this->{$subMethodName}();
				$eventAssets = $this->paginate();
				$this->set(compact('eventAssets'));
			}
			else
			{
				$this->errorMsg(__("Invalid URL"));
				$this->redirect("/");
			}
		}else
		{
			$this->errorMsg(__("Invalid Type"));
			$this->redirect("/");
		}

	}

	function __eventGallery()
	{
		if(!isset($this->params['named']['eventId']) || !isset($this->params['pass']['0']))
		{
			$this->__invalidUrl('Invalid parameter.');
		}
		$eventId = 	$this->params['named']['eventId'];
		$order = "created ASC";
		$userId = @$this->params['named']['userId'];

		unset($this->params['named']['userId']);
		$imageLimit = null;
		$this->paginate['conditions']['EventAsset.event_id'] =  $eventId;
		if($imageLimit > 0)
		{
			$imageIds = $this->EventAsset->find("list",array("conditions"=>$this->paginate['conditions'],'limit'=>$imageLimit,'fields'=>array("id")));
			$this->paginate['conditions']['EventAsset.id'] = $imageIds;
		}
		$assetToShow = null;
		if($userId)
		{
			$assetToShow = $this->EventAsset->field('id',array('EventAsset.event_id'=>$eventId,'EventAsset.status'=>EventAsset::PUBLISHED,'user_id'=>$userId),$order);
			$this->set("assetToShow",$assetToShow);
		}
		$eventData = $this->EventAsset->Event->find('first',array('conditions'=>array('Event.id'=>$eventId),'recursive'=>-1));
		$this->pageTitle = sprintf(__('%s\'s Gallery'),$eventData['Event']['title']);
		$this->set("event",$eventData);
		$this->set("eventGallery",true);
	}

	function __userGallery()
	{
		if(!isset($this->params['named']['user']))
		{
			$this->__invalidUrl('Invalid parameter.');
		}

		$userSlug = $this->params['named']['user'];
		$user = $this->EventAsset->User->find('first',array('conditions'=>array('User.slug'=>$userSlug),'recursive'=>-1));
		$this->set('user',$user);
		if(empty($user))
		{
			$this->__invalidUrl();
		}
			
		$this->EventAsset->setScope('published');
		$this->paginate['conditions'][] = array('EventAsset.user_id' => $user['User']['id']);
		$this->pageTitle = sprintf(__('%s \'s Gallery'),$user['User']['display_name']);
		$this->set("userGallery",true);
	}

	function __myGallery()
	{
		$authedUser = $this->Session->read('Auth.User');
		if(empty($authedUser))
		{
			$this->__invalidUrl(null,$this->referer());
		}
		$this->pageTitle = __('My Gallery');
		$this->EventAsset->setScope('published');
		$this->paginate['conditions'] = array('EventAsset.user_id'=>$authedUser['id']);
	}

	function admin_index($type = false)
	{
		$this->paginate['order'] = array('EventAsset.created DESC');
		$this->paginate['recursive'] = 0;
		if(isset($this->params['named']['limit']))
		{
			unset($this->params['named']['limit']);
			unset($this->passedArgs['limit']);
		}
		$this->paginate['limit'] = 150;
		$this->paginate['contain'] = array("Event");
		$this->paginate['conditions']['EventAsset.status'] = EventAsset::PUBLISHED;
		$assetToShow = null;
		if(isset($this->params['named']['show']))
		{
			$assetToShow = $this->params['named']['show'];
			unset($this->params['named']['show']);
			unset($this->passedArgs['show']);
		}
		$this->set("assetToShow",$assetToShow);
		if($type)
		{
			if(in_array($type, array_keys($this->indexMethods)))
			{
				$subMethodName = $this->indexMethods[$type]['method'];
				if(isset($this->indexMethods[$type]['title']))
				{
					$this->pageTitle = __($this->indexMethods[$type]['title']);
				}
				$this->{$subMethodName}();
				$eventAssets = $this->paginate();
				$this->set(compact('eventAssets'));
			}
			else
			{
				$this->errorMsg(__("Invalid URL"));
				$this->redirect("/");
			}
		}else
		{
			$this->errorMsg(__("Invalid Type"));
			$this->redirect("/");
		}
	}


	function __invalidUrl($msg = null, $url = null)
	{
		if(empty($msg))
		{
			$msg = __("Invalid URL");
		}
		if(empty($url))
		{
			$url = "/";
		}
		$this->errorMsg($msg);
		$this->redirect($url);
	}
}
?>